import { useEffect, useState } from 'react';
import { Tree } from 'antd';
import type { TreeProps } from 'antd/es/tree';
import { useMount } from 'ahooks';
import { isEmpty } from 'lodash';

import { queryResourceTree } from '@/services/resource-management';

type Key = string | number;

interface IAppProps {
  readonly?: boolean;
  value?: Key[];
  onChange?: (value: Key[]) => void;
}

type TreeItem = {
  title: string;
  key: string;
  children: TreeItem[];
  parentId: string;
};

const formatTreeData = (
  treeItemList: API.ResourceTreeItem[],
): {
  list: TreeItem[];
  map: Record<string, API.ResourceTreeItem>;
} => {
  const map = {} as Record<string, API.ResourceTreeItem>;
  const loop = (list: API.ResourceTreeItem[]): TreeItem[] => {
    if (!Array.isArray(list)) return [];
    return list.map((t) => {
      const { name, id, childResourcesList, parentId } = t;
      map[id] = t;
      return {
        title: name,
        key: id,
        children: loop(childResourcesList),
        parentId,
      };
    });
  };
  const res = loop(treeItemList);
  if (res.length) {
    return {
      list: res,
      map,
    };
  }
  return {
    list: [],
    map,
  };
};

const PermissionsTree: React.FC<IAppProps> = ({ readonly, value, onChange }) => {
  const [valueList, setValueList] = useState<Key[]>([]);
  const [treeData, setTreeData] = useState<TreeItem[]>([]);
  const [treeMap, setTreeMap] = useState<Record<string, API.ResourceTreeItem>>({});

  const getTree = async () => {
    const res = await queryResourceTree();
    if (!res.code && res.data) {
      const { list, map } = formatTreeData(res.data);
      setTreeData(list);
      setTreeMap(map);
      console.log(map, 66);
    }
  };

  useMount(() => {
    getTree();
  });

  useEffect(() => {
    if (value && !isEmpty(value)) {
      const newList = value.filter((v) => isEmpty(treeMap[v]?.childResourcesList));
      setValueList(newList);
    }
  }, [treeMap, value]);

  const onCheck: TreeProps['onCheck'] = (checkedKeys, e: any) => {
    // setValueList(checkedKeys.checked);
    if (Array.isArray(checkedKeys)) {
      setValueList([...checkedKeys]);
      onChange?.([...e?.halfCheckedKeys, ...checkedKeys]);
    }
  };

  if (isEmpty(treeData)) return null;
  return (
    <Tree
      checkable
      defaultExpandAll
      disabled={readonly}
      defaultExpandParent
      // checkStrictly
      // defaultSelectedKeys={value}
      checkedKeys={valueList}
      onCheck={onCheck}
      treeData={treeData}
    />
  );
};

export default PermissionsTree;
